from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.conf import settings
import re


class RbacMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """
        当用户请求进入的时候触发执行
        :param request:
        :return:
        """
        # 获取当前用户的url
        # 获取当前用户在session中保存的权限列表
        # 权限信息匹配
        # http://127.0.0.1:8000/customer/list/ customer/list/

        current_url = request.path_info
        for valid_url in settings.VALID_URL_LIST:
            if re.match(valid_url, current_url):
                return None

        permission_dict = request.session.get(settings.PREMISSION_SESSION_KEY)
        if not permission_dict:
            return HttpResponse('未获取到用户权限信息，请重新登录')
        flag = False
        url_record = [
            {'title': '首页',
             'url': '#',
             }
        ]
        for item in permission_dict.values():
            reg = "^%s$" % item['url']
            if re.match(reg, current_url):
                flag = True
                if  not item['pid']:
                    url_record.extend([{'title':item['title'],'url':item['url'],'class':'active'},
                                       ])
                else:
                    url_record.extend([{'title': item['p_title'], 'url': item['p_url']},
                                       {'title': item['title'], 'url': item['url'],'class':'active'}
                                       ])
                request.current_selected_permission = item['pid'] or item['id']
                request.url_record = url_record
                break
        if not flag:
            return HttpResponse('无权访问')
